package com.cff.shorturl.util;

public class Base62Util {
	private static String b64chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	private static int lessLen = 4;

	public static String encode(int src) {
		String res = "";
		int num = Math.abs(src);
		while (num > 0) {
			int decimal = num % 62;
			num = (int) Math.floor(num / 62);
			res = b64chars.charAt(decimal) + res;
		}
		int len = res.length();
		if (len < lessLen) {
			for (int i = lessLen; i > len; i--) {
				res = "0" + res;
			}
		}
		return res;
	}
	
	public static String encode(int src, int size) {
		String res = "";
		int num = Math.abs(src);
		while (num > 0) {
			int decimal = num % 62;
			num = (int) Math.floor(num / 62);
			res = b64chars.charAt(decimal) + res;
		}
		int len = res.length();
		if (len < size) {
			for (int i = size; i > len; i--) {
				res = "0" + res;
			}
		}
		return res;
	}

	public static int decode(String src) {
		int data = 0;
		for (int i = 0; i < src.length(); i++) {
			char c = src.charAt(i);
			int index = b64chars.indexOf(c);
			data = data*62 + index;
		}
		return data;
	}
}
